package org.spring.springboot.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class PayUtil {

	// 对所有待签名参数按照字段名的ASCII 码从小到大排序（字典序）后
	/**
	 * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
	 * 
	 * @param params
	 *            需要排序并参与字符拼接的参数组
	 * @return 拼接后字符串
	 */
	public static String createLinkString(Map<String, String> params) {
		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);
		String prestr = "";
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			String value = params.get(key);
			if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
				prestr = prestr + key + "=" + value;
			} else {
				prestr = prestr + key + "=" + value + "&";
			}
		}
		return prestr;
	}
	
	

 	//对所有待签名参数按照字段名的ASCII 码从小到大排序（字典序）后
    /** 
    * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
    * @param params 需要排序并参与字符拼接的参数组
    * @return 拼接后字符串
    */
   public static  String createLinkStringEncoder(Map<String, String> params) {
       List<String> keys = new ArrayList<String>(params.keySet());
       Collections.sort(keys);
       String prestr = "";
       try {
	       for (int i = 0; i < keys.size(); i++) {
	           String key = keys.get(i);
	           String value = params.get(key);
	           if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
					prestr = prestr + key + "=" +URLEncoder.encode(value,"UTF-8");
			
	           } else {
	               prestr = prestr + key + "=" + URLEncoder.encode(value,"UTF-8") + "&";
	           }
	       }
    	} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
       return prestr;
   }

	public static String getSixteenRandom(Integer length) {
		String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";// 含有字符和数字的字符串
		Random random = new Random();// 随机类初始化
		StringBuffer sb = new StringBuffer();// StringBuffer类生成，为了拼接字符串

		for (int i = 0; i < length; ++i) {
			int number = random.nextInt(62);// [0,62)

			sb.append(str.charAt(number));
		}
		return sb.toString();
	}
}
